package com.kunge2013.chatbi.advisor;

import lombok.AllArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @Author kunge2013
 * @Description 聊天记忆
 * @Date 2024/11/11 20:09
 * @Version 1.0
 */
@RestController
@RequestMapping("advisor/memory")
@AllArgsConstructor
public class MemoryAdvisorController {
    private final ChatMemory chatMemory = new InMemoryChatMemory();
    private final ZhiPuAiChatModel chatModel;
    private final SimpleLoggerAdvisor simpleLoggerAdvisor;
    private final ReReadingAdvisor readingAdvisor;

    @GetMapping(path = "chat")
    public Map chat(String chatId, String prompt) {
        ChatClient chatClient = ChatClient
                .builder(chatModel)
                .defaultAdvisors(new PromptChatMemoryAdvisor(chatMemory), simpleLoggerAdvisor, readingAdvisor)
                .build();
        String content = chatClient.prompt().user(prompt)
                .advisors(
                        a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)
                )
                .call()
                .content();
        return Map.of("content", content);
    }
}
